package net.ix.api;

import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import android.util.Log;

import net.ix.util.net.Post;

public class IXApi{
	private static String tag = "IXApi";
	private String apiUrl = "http://myshine.sinaapp.com/api/";
	private String apiMethod;
	private String apiAlt = "xml";
	
	private Map<String, String> postParams;
	private Map<String, String> params;
	
	private Post post;
	
	protected Document resXML;
	protected boolean stat = false;
	protected String errMsg;
	
	public IXApi(String method){
		apiMethod = method;
		params = new HashMap<String, String>();
	}
	public void addRequest(Map<String, String> p){
		params.putAll(p);
	}
	private void setRequest(){ 
		postParams = new HashMap<String, String>();
		postParams.put("method", apiMethod);
		postParams.put("alt", apiAlt);
		postParams.putAll(params);
	}
	public String getData(){
		setRequest();
		post = new Post();
		post.setUri(apiUrl);
		post.setQuerys(postParams);
		post.connect();
		String dataRes = post.getContent();
		return dataRes;
	}
	public void getXml() throws DocumentException{
		this.apiAlt = "xml";
		String xmlStr = this.getData();
		resXML = DocumentHelper.parseText(xmlStr);
	}

	public boolean checkOk(){
		String s = resXML.getRootElement().attributeValue("stat");
		Log.i(tag, s);
		if (s.equals("ok")){
			stat = true;
		} else if (s.equals("error")) {
			errMsg = resXML.selectSingleNode("/rsp/errmsg").getStringValue();
			Log.i(tag, errMsg);
		} else {
			errMsg = "unknow err";
		}
		return stat;
	}
	public String getErrMsg(){
		return errMsg;
	}
}